package com.mnt.washio.activities;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mnt.washio.R;
import com.mnt.washio.adapters.PaymentListAdapter;
import com.mnt.washio.objects.Card;
import com.mnt.washio.utils.SessionManager;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;
import com.mnt.washio.utils.network.ws.ApplyCouponWSControl;
import com.mnt.washio.utils.network.ws.BaseWSControl;
import com.mnt.washio.utils.network.ws.BaseWSControl.WebServiceFlag;
import com.mnt.washio.utils.network.ws.DeleteCardWSControl;
import com.mnt.washio.utils.network.ws.GetBalanceWSControl;
import com.mnt.washio.utils.network.ws.GetCreditCardListWSControl;
import com.parse.ParseUser;

public class PaymentActivity extends BaseActivity implements OnClickListener,
		WebServiceCommunicatorListener {

	private ListView mPaymentList;
	private PaymentListAdapter mAdapter;
	private Button mBtnAddCreaditCard;
	private Button mBtnApply, mBtnShare;
	private TextView mTvBalance;
	private EditText mEdtCouponCode;
	private ProgressDialog mLoadingDialog;
	private float mBalance;
	private boolean okBalance = false, okListCard = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_payment);
		initView();
		addListener();
		new GetBalanceWSControl(this, this, ParseUser.getCurrentUser()
				.getObjectId()).execute();
		String stripId = ParseUser
				.getCurrentUser().getString("stripeId");
		if(stripId != null){
			new GetCreditCardListWSControl(this, this, stripId).execute();
		} else{
			okListCard = true;
		}

	}

	private void setBalance(double balance) {
		DecimalFormat formater = new DecimalFormat("0.00");
		mTvBalance.setText(getString(R.string.txt_payment_credit,
				formater.format(balance)));
	}

	@Override
	protected void initView() {
		super.initView();

		mLoadingDialog = new ProgressDialog(this);
		mLoadingDialog.setMessage("Loading...");
		mLoadingDialog.setCancelable(false);

		mPaymentList = (ListView) findViewById(R.id.list_payments);

		mBtnApply = (Button) findViewById(R.id.btn_apply);
		mBtnShare = (Button) findViewById(R.id.btn_share);
		mTvBalance = (TextView) findViewById(R.id.tv_balance);
		mEdtCouponCode = (EditText) findViewById(R.id.edt_coupon_code);

		mBtnAddCreaditCard = (Button) findViewById(R.id.btn_add_credit_card);

		List<Card> cards;
		if (SessionManager.getSessionManager(this).getCardList() != null) {
			cards = SessionManager.getSessionManager(this).getCardList();
		} else {
			cards = new ArrayList<Card>();
		}
		mAdapter = new PaymentListAdapter(this, cards) {

			@Override
			public void onRemoveCard(Card card, int position) {
				new DeleteCardWSControl(PaymentActivity.this,
						PaymentActivity.this, ParseUser.getCurrentUser()
								.getString("stripeId"), card).execute();
			}

		};
		mPaymentList.setAdapter(mAdapter);

	}

	public void addListener() {
		mBtnAddCreaditCard.setOnClickListener(this);
		mBtnApply.setOnClickListener(this);
		mBtnShare.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.btn_add_credit_card:
			intent = new Intent(PaymentActivity.this,
					RegisterStep3Activity.class);
			startActivityForResult(intent, 100);
			break;
		case R.id.btn_apply:
			String couponCode = mEdtCouponCode.getText().toString().trim();
			if (couponCode.length() == 0) {
				Toast.makeText(this, "Please enter coupon code!",
						Toast.LENGTH_SHORT).show();
			} else {
				new ApplyCouponWSControl(this, this, ParseUser.getCurrentUser()
						.getObjectId(), couponCode).execute();
			}
			break;
		case R.id.btn_share:
			intent = new Intent(PaymentActivity.this, ShareActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	public void onConnectionOpen(BaseWSControl wsControl, WebServiceFlag flag) {
		mLoadingDialog.show();
	}

	@Override
	public void onConnectionError(BaseWSControl wsControl, WebServiceFlag flag,
			String error) {
		mLoadingDialog.dismiss();
		Toast.makeText(this, error, Toast.LENGTH_LONG).show();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onConnectionDone(BaseWSControl wsControl, WebServiceFlag flag,
			Object result) {
		if (flag == WebServiceFlag.GET_BALANCE) {
			if (result != null) {
				mBalance = (Float) result;
				setBalance(mBalance);
			}

			okBalance = true;
			hideProgressBar();
		} else if (flag == WebServiceFlag.APPLY_COUPON) {
			if (result != null) {
				if (((Boolean) result)) {
					Toast.makeText(this, "Coupon applied!", Toast.LENGTH_LONG)
							.show();
					mEdtCouponCode.setText("");
					mBalance += 10.0;
					setBalance(mBalance);
				} else {
					Toast.makeText(this, "Apply fail!", Toast.LENGTH_LONG)
							.show();
					mEdtCouponCode.setText("");
				}
			}

			mLoadingDialog.dismiss();
		} else if (flag == WebServiceFlag.GET_CREDIT_CARDS) {
			List<Card> cards = (List<Card>) result;
			SessionManager.getSessionManager(this).setCardList(cards);
			mAdapter.clear();
			for (Card card : cards) {
				mAdapter.add(card);
			}
			mAdapter.notifyDataSetChanged();
			
			okListCard = true;
			hideProgressBar();
		} else if (flag == WebServiceFlag.REMOVE_CARD) {
			if (result != null) {
				DeleteCardWSControl ws = (DeleteCardWSControl) wsControl;
				if ((Boolean) result) {
					SessionManager.getSessionManager(this).getCardList().remove(ws.card);
					mAdapter.remove(ws.card);
				} else {
					Toast.makeText(this, "Remove card fail!", Toast.LENGTH_LONG)
							.show();
				}
			}

			mLoadingDialog.dismiss();
		}
	}

	@Override
	public void onUpdateData(BaseWSControl wsControl, WebServiceFlag flag,
			Object data) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == 100) {
				Card card = (Card) data.getSerializableExtra("card");
				mAdapter.add(card);
				mAdapter.notifyDataSetChanged();
				if (!SessionManager.getSessionManager(this).getCardList()
						.contains(card)) {
					SessionManager.getSessionManager(this).getCardList()
							.add(card);
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void hideProgressBar() {
		if (okBalance && okListCard && mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
}
